//
//  ZThread.h
//  Part of Z-Way.C library
//
//  Created by Pavel Kulaha.
//
//  Copyright (c) 2021 Z-Wave.Me
//  All rights reserved
//  info@z-wave.me
//
//  This source file is subject to the terms and conditions of the
//  Z-Wave.Me Software License Agreement which restricts the manner
//  in which it may be used.
//
#ifndef zthread_h
#define zthread_h

#if defined(_WINDOWS)
typedef HANDLE ZWTHREAD;

// DWORD WINAPI ThreadProc(_In_ LPVOID lpParameter);
typedef DWORD ZW_PROCRET;

#define current_thread() GetCurrentThread()
#elif defined(__FREERTOS__)
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <freertos/semphr.h>

typedef void ZW_PROCRET;
typedef TaskHandle_t ZWTHREAD;
#define current_thread() xTaskGetCurrentTaskHandle()
#else
#include <pthread.h>

typedef void *ZW_PROCRET;
typedef pthread_t ZWTHREAD;
#define current_thread() pthread_self()
#endif

typedef ZW_PROCRET (*ZWThreadProc_t)(void *args);

ZWEXPORT_PRIVATE void set_thread_name(const char *name);

typedef struct _ZThreadCreateSettings_s
{
    size_t stack_size;
    ZWCSTR name;
} _ZThreadCreateSettings_t;

ZWEXPORT_PRIVATE ZWError _zthread_create(ZWTHREAD *pthread, ZWThreadProc_t proc, void *args, const _ZThreadCreateSettings_t *settings);
ZWEXPORT_PRIVATE ZWError _zthread_wait_completion(ZWTHREAD *pthread);
ZWEXPORT_PRIVATE ZWError _zthread_feed_watchdog(void);
ZWEXPORT_PRIVATE void _zthread_yield(void);
ZWEXPORT_PRIVATE ZWError _zthread_check_stack_size(size_t stack_size);
static inline void _zthread_settings_init(_ZThreadCreateSettings_t *settings, size_t stack_size, ZWCSTR name)
{
    settings->stack_size = stack_size;
    settings->name = name;
};

#if defined(__FREERTOS__)
#define ZTHREAD_RETURN_RET(STATUS) \
    return;
#else
#define ZTHREAD_RETURN_RET(STATUS) \
    return STATUS;
#endif

#define ZTHREAD_RETURN_STATUS_SUCCESS (ZW_PROCRET)0
#define ZTHREAD_RETURN_STATUS_FAILURE (ZW_PROCRET)1

#endif // zthread_h
